# TODO 设计更人性化的转换方法
def doc_to_docx():
    """将 .doc文件转换成 .docx文件"""
    import os
    from win32com import client

    wd = client.Dispatch('Word.Application')  # word程序对象
    path = r'C:\Users\Mr-Lu\Desktop\djbh\process_documents\template'
    for root, dirs, files in os.walk(path):
        _r = root.replace('/', '\\')
        for file in files:
            if file.endswith('.doc'):
                _f = os.path.join(root, file)
                doc = wd.Documents.Open(_f)
                doc.SaveAs(f'{_f}x', FileFormat=12)  # 另存为本地
                doc.Close()


# TODO 在web界面中补充缺失的一些信息 比如被测单位负责人...等
def get_doc_info(file_path) -> (dict, None):
    """
    获取报告的信息
    :param file_path 测评报告的文件路径 str
    """
    from os.path import basename
    import re
    from docx import Document
    from extensions import log_gen

    if len(file_path) == 0:
        return None, None
    report_name = basename(file_path).split('_')  # list
    if '测评报告' not in file_path:  # 判断报告
        log_gen.lgr.error('[ file err ] 传入的文件不是测评报告')  # 写入日志
        return None, None

    base_data = {}
    struct_data = {}

    # <editor-fold desc="从文档名称中获取项目编号">
    pj_num = report_name[0]
    # TODO 注意项目编号为自定义类型 非泛类型
    if pj_num[0:7].isdigit():
        base_data['$项目编号$'] = pj_num
    else:
        base_data['$项目编号$'] = '/'

    f = Document(file_path)  # docx obj
    # </editor-fold>

    # TODO 使用遍历的方法避免扩展表引起的索引变动问题
    # <editor-fold desc="遍历文档表格获取信息">
    for table in f.tables:
        if table.cell(0, 0).text == '被测对象':
            # <editor-fold desc="网络安全等级测评基本信息表">
            # <editor-fold desc="被测对象">
            base_data['$被测对象$'] = table.cell(1, 1).text
            base_data['$安全保护等级$'] = table.cell(1, 3).text
            base_data['$备案证明编号$'] = table.cell(2, 1).text
            # </editor-fold>
            # <editor-fold desc="被测单位">
            table_0 = table.cell(3, 0).tables[0]  # 被测单位
            base_data['$被测单位$'] = table_0.cell(1, 1).text
            base_data['$被测单位地址$'] = table_0.cell(2, 1).text
            # TODO 注意合并单元格的索引问题
            base_data['$被测单位邮编$'] = table_0.cell(2, 5).text
            base_data['$被测单位联系人姓名$'] = table_0.cell(3, 2).text
            base_data['$被测单位联系人职务$'] = table_0.cell(3, 4).text
            base_data['$被测单位联系人部门$'] = table_0.cell(4, 2).text
            base_data['$被测单位联系人办公电话$'] = table_0.cell(4, 4).text
            base_data['$被测单位联系人移动电话$'] = table_0.cell(5, 2).text
            base_data['$被测单位联系人电子邮件$'] = table_0.cell(5, 4).text
            # </editor-fold>
            # <editor-fold desc="测评单位">
            table_1 = table.cell(4, 0).tables[0]  # 测评单位
            base_data['$测评单位$'] = table_1.cell(1, 1).text
            base_data['$测评单位机构代码$'] = table_1.cell(1, 5).text
            base_data['$测评单位地址$'] = table_1.cell(2, 1).text
            base_data['$测评单位邮编$'] = table_1.cell(2, 5).text
            base_data['$测评单位联系人姓名$'] = table_1.cell(3, 2).text
            base_data['$测评单位联系人职务$'] = table_1.cell(3, 4).text
            base_data['$测评单位联系人部门$'] = table_1.cell(4, 2).text
            base_data['$测评单位联系人办公电话$'] = table_1.cell(4, 4).text
            base_data['$测评单位联系人移动电话$'] = table_1.cell(5, 2).text
            base_data['$测评单位联系人电子邮件$'] = table_1.cell(5, 4).text
            # </editor-fold>
            # </editor-fold>
        elif table.cell(0, 0).text == '测评结论和综合得分':
            # <editor-fold desc="等级测评结论">
            # <editor-fold desc="测评结论和综合得分">
            struct_data['$被测对象描述$'] = table.cell(3, 1).text  # 表格中段落的字符串保留\r\n
            struct_data['$安全状况描述$'] = table.cell(4, 1).text
            base_data['$等级测评结论$'] = table.cell(5, 1).text
            base_data['$综合得分$'] = table.cell(5, 3).text
            # </editor-fold>
            # </editor-fold>
        elif table.cell(0, 0).text == '等级测评结论扩展表（云计算安全）':
            base_data['$扩展要求$'] = '云计算'
        elif table.cell(0, 1).text == '设备名称':  # 漏扫结果汇总表
            if table.cell(0, 2).text == '系统及版本':
                if struct_data.__contains__('$漏扫对象$'):  # JA/JB/JC...多个接入点的表
                    struct_data['$漏扫对象$'] += [table.cell(r, 1).text for r in range(2, len(table.rows))]
                struct_data['$漏扫对象$'] = [table.cell(r, 1).text for r in range(2, len(table.rows))]
        elif table.cell(0, 1).text == '文档名称':  # 文档/内容
            if struct_data.__contains__('$制度文档$'):  # 过滤重复
                continue
            struct_data['$制度文档$'] = [
                [table.cell(row, 1).text] + [table.cell(row, 2).text]
                for row in range(1, len(table.rows))]
        elif table.cell(0, len(table.columns) - 1).text == '测评项':
            ds = []
            index = 1
            for row_n in range(1, len(table.rows)):
                if table.rows[row_n].cells[0].text == table.rows[row_n].cells[1].text:
                    ds.append(table.rows[row_n].cells[0].text)
                    index = 1
                else:
                    ds.append([
                        table.rows[row_n].cells[4].text,
                        str(index),
                        table.rows[row_n].cells[5].text,
                        table.rows[row_n].cells[6].text,
                        table.rows[row_n].cells[1].text,
                        table.rows[row_n].cells[2].text,
                    ])
                    index += 1
            struct_data['$问题建议$'] = ds
        elif table.cell(0, len(table.columns) - 1).text == '整改建议':
            ds = []
            dr = []  # 存储行数据
            for row_n in range(1, len(table.rows)):
                if table.rows[row_n].cells[0].text == table.rows[row_n].cells[1].text:
                    ds.append(table.rows[row_n].cells[0].text)
                else:
                    for num in range(6):
                        if num == 5:
                            struct_data['$问题建议$'][row_n - 1].append(
                                table.rows[row_n].cells[5].text)
                        dr.append(table.rows[row_n].cells[num].text)
                    ds.append(dr)
                    dr = []  # 清空容器
            struct_data['$安全问题整改建议$'] = ds
        elif table.cell(0, len(table.columns) - 1).text == '风险等级':
            ds = []
            dr = []
            for row_n in range(1, len(table.rows)):
                if table.rows[row_n].cells[0].text == table.rows[row_n].cells[1].text:
                    ds.append(table.rows[row_n].cells[0].text)
                else:
                    for num in range(8):
                        dr.append(table.rows[row_n].cells[num].text)
                    ds.append(dr)
                    dr = []
            struct_data['$安全问题风险分析$'] = ds
        else:
            # 数据回收处理
            if not base_data.__contains__('$扩展要求$'):
                base_data['$扩展要求$'] = '/'
    # </editor-fold>
    # <editor-fold desc="遍历文档段落获取信息">
    documents = f.paragraphs
    for i, doc in enumerate(documents):
        if len(doc.text) == 0:
            continue
        if doc.style.name == 'Heading 2':
            if doc.text == '测评过程':  # 获取测评过程的时间参数
                reg = r'\d{4}年\d{2}月\d{2}日|\d{2}月\d{2}日'  # 正则方法
                keys_list = [
                    ['$测评准备起始时间$', '$测评准备结束时间$'],
                    ['$方案编制起始时间$', '$方案编制结束时间$'],
                    ['$现场实施起始时间$', '$现场实施结束时间$'],
                    ['$报告编制起始时间$', '$报告编制结束时间$']
                ]
                for num, keys in enumerate(keys_list, 2):
                    process_t = re.findall(reg, documents[i + num].text)
                    base_data[keys[0]] = process_t[0]
                    if '年' in process_t[1]:
                        base_data[keys[1]] = process_t[1]
                    else:
                        base_data[keys[1]] = f'{process_t[0][0:5]}{process_t[1]}'
                break  # 执行第一次
        elif doc.style.name == 'Normal':
            if doc.text[0:4] == '报告编号':
                if base_data.__contains__('$报告编号$'):
                    continue
                base_data['$报告编号$'] = doc.text[5:]
    # </editor-fold>

    return None if len(base_data) == 0 else base_data, None if len(struct_data) == 0 else struct_data


def replace_doc_info(data, report_p, template_p, project_p) -> (None, int):
    """
    替换word文件的内容
    :param data 键值数据 dict
        {'$key$': 'value'}
    :param report_p 测评报告的路径
    :param template_p 归档模板的路径
    :param project_p 工程的路径
    """
    from os import path as op
    import pythoncom
    from os import remove
    from win32com import client
    from docx import Document
    # 单元格对齐方式
    from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
    # 段落对齐方式
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    from config.doc_config import (
        template_file, template_map
    )
    from core.sysuser import split_path
    from extensions import log_gen, log_err

    if data is None:
        return None
    try:
        pythoncom.CoInitialize()  # 使用线程进行数据处理
        wd = client.DispatchEx('Word.Application')  # Ex避免现有word进程数据被误用
    except Exception as e:
        log_err.set_log_message('ERROR')
        return None
    wd.Visible = False  # 显示word程序
    wd.DisplayAlerts = 0  # 不显示告警框

    # 通用方法
    for file in template_file:
        temp_p = split_path(template_p, file)
        pj_p = split_path(project_p, file)

        if not template_map.__contains__(file):
            continue  # 临时过滤未处理的文件
        if not op.exists(temp_p):
            log_gen.lgr.error(f'[ file err ] 读取的文件 -- {file} -- 不存在')  # 写入日志
            continue  # 过滤实际目录中未存在的文件
        if op.exists(pj_p):
            remove(pj_p)  # 移除旧的文件 保证前台数据可以进行更新
        # 执行 python-docx库
        if file == 'ZJXP QR26-08 现场测评授权书.docx':
            f = Document(temp_p)
            for table in f.tables:
                if table.cell(0, 1).text == '设备名称（型号）/系统名称' and data.__contains__('$漏扫对象$'):
                    for num, scan in enumerate(data['$漏扫对象$']):
                        table.add_row()
                        table.cell(num + 1, 0).paragraphs[0].text = str(num + 1)
                        table.cell(num + 1, 1).paragraphs[0].text = scan
            f.save(pj_p)
            temp_p = pj_p  # 保证后续替换在新的文件中执行
        elif file == 'ZJXP QR26-10 文档接收 归还清单.docx':
            f = Document(temp_p)
            for table in f.tables:
                if table.cell(0, 1).text == '文件名称' and data.__contains__('$制度文档$'):
                    for num, rag in enumerate(data['$制度文档$']):
                        table.add_row()
                        table.cell(num + 1, 0).paragraphs[0].text = str(num + 1)
                        table.cell(num + 1, 1).paragraphs[0].text = rag[0]
                        table.cell(num + 1, 2).paragraphs[0].text = rag[1]
            f.save(pj_p)
            temp_p = pj_p  # 保证后续替换在新的文件中执行
        elif file == 'ZJXP QR26-13 网络安全问题汇总及整改建议.docx':
            f = Document(temp_p)
            for table in f.tables:
                if table.cell(0, 0).text == '安全层面' and data.__contains__('$问题建议$'):
                    for num, rag in enumerate(data['$问题建议$']):
                        table.add_row()
                        if isinstance(rag, str):
                            for mer in range(1, 7):
                                table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                            table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].text = rag
                        else:
                            for n, col in enumerate(rag):
                                table.cell(num + 1, n).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                                table.cell(num + 1, n).paragraphs[0].text = rag[n]
            f.save(pj_p)
            temp_p = pj_p  # 保证后续替换在新的文件中执行
        elif file == 'ZJXP QR26-09 测评结果记录表.docx':
            wd.Documents.Open(report_p)  # 打开原始文档
            doc = wd.ActiveDocument

            # 通过range判断选范围
            start = end = 0  # 默认不复制
            para = doc.Paragraphs  # 段落的迭代器
            for p in para:
                if p.Range.Text == '单项测评结果记录\r':
                    if p.OutlineLevel == 1:
                        start = p.Range.End + 1
                elif p.Range.Text == '漏洞扫描结果记录\r':
                    if p.OutlineLevel == 1:
                        end = p.Range.Start - 1  # 注意 在复制选中内容时 光标的范围要-1
            if end == 0 or end < start:
                end = start  # 防止end未索引到正确值

            doc.Range(start, end).Select()
            wd.Selection.Copy()  # 复制选择的内容

            wd.ActiveDocument.Close()  # 关闭文档

            doc_new = wd.Documents.Open(temp_p)  # 打开新的文档
            # word_app.Documents(doc_new).Activate()  # 激活新的文档

            wd.Selection.MoveRight(1, doc_new.Range().End - 1)  # 按字频移动 光标右边移动到文末前一个位置
            wd.Selection.TypeParagraph()  # 插入回车
            wd.Selection.InsertBreak()  # 插入页
            wd.Selection.Paste()  # 粘贴选择的内容

            doc_new.SaveAs(pj_p)  # 保存新的文档
            doc_new.Close()  # 关闭文档

            temp_p = pj_p  # 保证后续替换在新的文件中执行
        elif file == '$被测对象$_（整改建议书）.docx':
            pj_p = pj_p.replace('$被测对象$', data['$被测对象$'])  # TODO key error
            f = Document(temp_p)
            for table in f.tables:
                if table.cell(0, len(table.columns) - 1).text == '风险等级' and data.__contains__('$安全问题风险分析$'):
                    for num, rag in enumerate(data['$安全问题风险分析$']):
                        table.add_row()
                        if isinstance(rag, str):
                            for mer in range(1, 8):
                                table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                            table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].text = rag
                        else:
                            for n, col in enumerate(rag):
                                table.cell(num + 1, n).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                                table.cell(num + 1, n).paragraphs[0].text = rag[n]
                if table.cell(0, len(table.columns) - 1).text == '整改建议' and data.__contains__('$安全问题整改建议$'):
                    for num, rag in enumerate(data['$安全问题整改建议$']):
                        table.add_row()
                        if isinstance(rag, str):
                            for mer in range(1, 6):
                                table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                            table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].text = rag
                        else:
                            for n, col in enumerate(rag):
                                table.cell(num + 1, n).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                                table.cell(num + 1, n).paragraphs[0].text = rag[n]
            f.save(pj_p)
            temp_p = pj_p  # 保证后续替换在新的文件中执行
        elif file == '$被测对象$_（整改规划书）.docx':
            pj_p = pj_p.replace('$被测对象$', data['$被测对象$'])  # TODO key error
            f = Document(temp_p)
            for table in f.tables:
                if table.cell(0, len(table.columns) - 1).text == '风险等级' and data.__contains__('$安全问题风险分析$'):
                    for num, rag in enumerate(data['$安全问题风险分析$']):
                        table.add_row()
                        if isinstance(rag, str):
                            for mer in range(1, 7):
                                table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                            table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].text = rag
                        else:
                            for n in [0, 2, 3, 4, 5, 6, 7]:
                                if n != 0:
                                    m = n - 1
                                else:
                                    m = n
                                table.cell(num + 1, m).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                                table.cell(num + 1, m).paragraphs[0].text = rag[n]
                if table.cell(0, len(table.columns) - 1).text == '整改负责人' and data.__contains__(
                        '$安全问题整改建议$'):
                    for num, rag in enumerate(data['$安全问题整改建议$']):
                        table.add_row()
                        if isinstance(rag, str):
                            for mer in range(1, 7):
                                table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                            table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                            table.cell(num + 1, 0).paragraphs[0].text = rag
                        else:
                            cache = '目前实现可信验证机制的成本过高且技术不成熟，暂缓整改'
                            ti = data['$测评准备起始时间$']
                            ti = ti.replace(ti[:4], str(int(ti[:4]) + 1))  # 追加一年
                            way = None
                            if len(data['$被测单位联系人办公电话$']) > 3:
                                way = data['$被测单位联系人办公电话$']
                            elif len(data['$被测单位联系人移动电话$']) > 3:
                                way = data['$被测单位联系人移动电话$']
                            elif len(data['$被测单位联系人电子邮件$']) > 3:
                                way = data['$被测单位联系人电子邮件$']
                            else:
                                way = data['$被测单位$']
                            contact = data['$被测单位联系人姓名$'] + '\n' + way  # 负责人信息
                            for n in [0, 2, 3, 4, 5, 6]:
                                if n != 0:
                                    m = n - 1
                                else:
                                    m = n
                                if n == 6:
                                    if '可信根' in rag[3]:
                                        table.cell(num + 1, m).paragraphs[0].text = cache
                                        table.cell(num + 1, m + 1).paragraphs[0].text = '/'
                                    else:
                                        table.cell(num + 1, m).paragraphs[0].text = ti
                                        table.cell(num + 1, m + 1).paragraphs[0].text = contact
                                else:
                                    table.cell(num + 1, m).paragraphs[0].text = rag[n]
                                table.cell(num + 1, m).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                                table.cell(num + 1, m + 1).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            f.save(pj_p)
            temp_p = pj_p  # 保证后续替换在新的文件中执行

        # 执行 win32com库
        if template_map.__contains__(file):  # 防止map未设计
            docx = wd.Documents.Open(temp_p)  # document
            select = wd.Selection  # selection 需要在指定Open的文档代码后面设置 否则保存
            for rep in template_map[file]:
                if data.__contains__(rep):  # 过滤data中不存在的关键字
                    select.Find.Execute(
                        rep, False, False, False,
                        False, False, True, 1,
                        False, data[rep], 2)
            docx.SaveAs(pj_p)  # save as
            docx.Close()  # close

    # TODO 多个文档处理完后统一关闭接口程序
    wd.Quit(0)  # 关闭程序  参数: 0 不保存待定的更改
    del wd  # 关闭进程
    pythoncom.CoUninitialize()

    return 1


def replace_doc_info_single(data, report_p, template_p, project_p) -> (None, int):
    """单文件测试"""
    from os import path as op
    import pythoncom
    from os import remove
    from win32com import client
    from docx import Document
    # 单元格对齐方式
    from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
    # 段落对齐方式
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    from config.doc_config import (
        template_file, template_map
    )
    from core.sysuser import split_path
    from extensions import log_gen, log_err

    # return None  # 调试

    if data is None:
        return None
    try:
        pythoncom.CoInitialize()  # 使用线程进行数据处理
        wd = client.DispatchEx('Word.Application')  # Ex避免现有word进程数据被误用
    except Exception as e:
        log_err.set_log_message('ERROR')
        return None
    wd.Visible = False  # 显示word程序
    wd.DisplayAlerts = 0  # 不显示告警框

    # 单个文件调试法
    file = template_file[1]  # 指定的文件
    # ---------------------------------------
    temp_p = split_path(template_p, file)
    pj_p = split_path(project_p, file)
    # 执行 python-docx库
    if file == '$被测对象$_（整改规划书）.docx':
        pj_p = pj_p.replace('$被测对象$', data['$被测对象$'])  # TODO key error
        f = Document(temp_p)
        for table in f.tables:
            if table.cell(0, len(table.columns) - 1).text == '风险等级' and data.__contains__('$安全问题风险分析$'):
                for num, rag in enumerate(data['$安全问题风险分析$']):
                    table.add_row()
                    if isinstance(rag, str):
                        for mer in range(1, 7):
                            table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                        table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                        table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                        table.cell(num + 1, 0).paragraphs[0].text = rag
                    else:
                        for n in [0, 2, 3, 4, 5, 6, 7]:
                            if n != 0:
                                m = n - 1
                            else:
                                m = n
                            table.cell(num + 1, m).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, m).paragraphs[0].text = rag[n]
            if table.cell(0, len(table.columns) - 1).text == '整改负责人' and data.__contains__('$安全问题整改建议$'):
                for num, rag in enumerate(data['$安全问题整改建议$']):
                    table.add_row()
                    if isinstance(rag, str):
                        for mer in range(1, 7):
                            table.cell(num + 1, mer - 1).merge(table.cell(num + 1, mer))
                        table.cell(num + 1, 0).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                        table.cell(num + 1, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                        table.cell(num + 1, 0).paragraphs[0].text = rag
                    else:
                        cache = '目前实现可信验证机制的成本过高且技术不成熟，暂缓整改'
                        ti = data['$测评准备起始时间$']
                        ti = ti.replace(ti[:4], str(int(ti[:4]) + 1))  # 追加一年
                        way = None
                        if len(data['$被测单位联系人办公电话$']) > 3:
                            way = data['$被测单位联系人办公电话$']
                        elif len(data['$被测单位联系人移动电话$']) > 3:
                            way = data['$被测单位联系人移动电话$']
                        elif len(data['$被测单位联系人电子邮件$']) > 3:
                            way = data['$被测单位联系人电子邮件$']
                        else:
                            way = data['$被测单位$']
                        contact = data['$被测单位联系人姓名$'] + '\n' + way  # 负责人信息
                        for n in [0, 2, 3, 4, 5, 6]:
                            if n != 0:
                                m = n - 1
                            else:
                                m = n
                            if n == 6:
                                if '可信根' in rag[3]:
                                    table.cell(num + 1, m).paragraphs[0].text = cache
                                    table.cell(num + 1, m + 1).paragraphs[0].text = '/'
                                else:
                                    table.cell(num + 1, m).paragraphs[0].text = ti
                                    table.cell(num + 1, m + 1).paragraphs[0].text = contact
                            else:
                                table.cell(num + 1, m).paragraphs[0].text = rag[n]
                            table.cell(num + 1, m).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                            table.cell(num + 1, m + 1).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
        f.save(pj_p)
        temp_p = pj_p  # 保证后续替换在新的文件中执行

    # 执行 win32com库
    if template_map.__contains__(file):  # 防止map未设计
        docx = wd.Documents.Open(temp_p)  # document
        select = wd.Selection  # selection 需要在指定Open的文档代码后面设置 否则保存
        for rep in template_map[file]:
            if data.__contains__(rep):  # 过滤data中不存在的关键字
                select.Find.Execute(rep, False, False, False, False, False, True, 1, False, data[rep], 2)
        docx.SaveAs(FileName=pj_p)  # save as
        docx.Close()  # close

    # TODO 多个文档处理完后统一关闭接口程序
    wd.Quit(0)  # 关闭程序  参数: 0 不保存待定的更改
    del wd  # 关闭进程
    pythoncom.CoUninitialize()

    return 1


if __name__ == '__main__':
    pass
